package com.hadoop.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TradeSkuOrderBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.HbaseUtil;
import com.bw.gmall.realtime.common.util.RedisUtil;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.api.StatefulRedisConnection;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.AsyncConnection;
import org.apache.hadoop.hbase.client.Connection;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class DwsTradeSkuOrderWindowAsyncCache extends BaseApp {
    public static void main(String[] args) throws Exception {
        new DwsTradeSkuOrderWindowAsyncCache().start(10029, 4, Constant.DWS_TRADE_SKU_ORDER_WINDOW, Constant.TOPIC_DWD_TRADE_ORDER_DETAIL);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1.清洗数据
        SingleOutputStreamOperator<JSONObject> etlStream = stream.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    Long ts = jsonObject.getLong("ts");
                    String skuId = jsonObject.getString("sku_id");
                    if (skuId != null && ts != null) {
                        jsonObject.put("ts", ts * 1000);
                        collector.collect(jsonObject);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //2.添加水位线
        SingleOutputStreamOperator<JSONObject> wmStream = etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts");
            }
        }));
        // 3.先分组 校正数据
        SingleOutputStreamOperator<TradeSkuOrderBean> processStream = wmStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getString("id");
            }
        }).process(new KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>() {
            MapState<String, BigDecimal> mapState;

            @Override
            public void open(Configuration parameters) throws Exception {
                MapStateDescriptor<String, BigDecimal> stateDescriptor = new MapStateDescriptor<String, BigDecimal>("order_state", String.class, BigDecimal.class);
                stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(10)).build());
                mapState = getRuntimeContext().getMapState(stateDescriptor);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>.Context context, Collector<TradeSkuOrderBean> collector) throws Exception {
//                // 因为有回撤流的影响，所以要校正数据
//                // 200-->300
//                BigDecimal stateOriginalAmount = mapState.get("originalAmount");
//                // 单价
//                // 100
//                // 100
//                BigDecimal orderPrice = jsonObject.getBigDecimal("order_price");
//                // 购买的数量
//                // 2
//                // 3
//                BigDecimal skuNum = jsonObject.getBigDecimal("sku_num");
//                // 原始金额
//                // 200
//                // 300
//                BigDecimal originalAmount = orderPrice.multiply(skuNum);
//                // 往下发
//                BigDecimal oa = BigDecimal.valueOf(0.0f);
//                if (stateOriginalAmount == null){
//                    mapState.put("originalAmount",originalAmount);
//                    oa = originalAmount;// 200
//                }else{
//                    mapState.put("originalAmount",originalAmount);
//                    oa = originalAmount.subtract(stateOriginalAmount);// 100
//                }


                // 取出流的金额
                BigDecimal splitTotalAmount = jsonObject.getBigDecimal("split_total_amount");
                BigDecimal splitActivityAmount = jsonObject.getBigDecimal("split_activity_amount");
                BigDecimal splitCouponAmount = jsonObject.getBigDecimal("split_coupon_amount");

                // 取出购买的数量
                BigDecimal sku_num = jsonObject.getBigDecimal("sku_num");
                // 单机
                BigDecimal orderPrice = jsonObject.getBigDecimal("order_price");

                // 计算原始金额
                BigDecimal originalAmount = orderPrice.multiply(sku_num);

                // 取状态的数据
                BigDecimal split_total_amount = mapState.get("splitTotalAmount");
                BigDecimal split_activity_amount = mapState.get("splitActivityAmount");
                BigDecimal split_coupon_amount = mapState.get("splitCouponAmount");
                BigDecimal original_amount = mapState.get("originalAmount");


                // 如果状态没有 ，默认赋值成0
                split_total_amount = split_total_amount == null ? new BigDecimal(0) : split_total_amount;
                split_activity_amount = split_activity_amount == null ? new BigDecimal(0) : split_activity_amount;
                split_coupon_amount = split_coupon_amount == null ? new BigDecimal(0) : split_coupon_amount;
                original_amount = original_amount == null ? new BigDecimal(0) : original_amount;


                String skuId = jsonObject.getString("sku_id");
                String skuName = jsonObject.getString("sku_name");
                String id = jsonObject.getString("id");
                Long ts = jsonObject.getLong("ts");


                // 往下游发
                collector.collect(TradeSkuOrderBean.builder().skuId(skuId).orderDetailId(id).orderAmount(splitTotalAmount.subtract(split_total_amount)).originalAmount(originalAmount.subtract(original_amount)).activityReduceAmount(splitActivityAmount.subtract(split_activity_amount)).couponReduceAmount(splitCouponAmount.subtract(split_coupon_amount)).skuName(skuName).ts(ts).build());


                // 更新状态 把当前的金额存进去
                mapState.put("splitTotalAmount", splitTotalAmount);
                mapState.put("splitActivityAmount", splitActivityAmount);
                mapState.put("splitCouponAmount", splitCouponAmount);
                mapState.put("originalAmount", originalAmount);
            }
        });
        // 分组SKU_ID 开窗 聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> reduceStream = processStream.keyBy(new KeySelector<TradeSkuOrderBean, String>() {
            @Override
            public String getKey(TradeSkuOrderBean tradeSkuOrderBean) throws Exception {
                return tradeSkuOrderBean.getSkuId();
            }
        }).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10))).reduce(new ReduceFunction<TradeSkuOrderBean>() {
            @Override
            public TradeSkuOrderBean reduce(TradeSkuOrderBean value1, TradeSkuOrderBean value2) throws Exception {
                value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                value1.setCouponReduceAmount(value1.getCouponReduceAmount().add(value2.getCouponReduceAmount()));
                value1.setActivityReduceAmount(value1.getActivityReduceAmount().add(value2.getActivityReduceAmount()));
                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                return value1;
            }
        }, new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
            @Override
            public void process(String s, ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>.Context context, Iterable<TradeSkuOrderBean> iterable, Collector<TradeSkuOrderBean> collector) throws Exception {
                TimeWindow window = context.window();
                String start = DateFormatUtil.tsToDateTime(window.getStart());
                String end = DateFormatUtil.tsToDateTime(window.getStart());
                TradeSkuOrderBean tradeSkuOrderBean = iterable.iterator().next();
                tradeSkuOrderBean.setStt(start);
                tradeSkuOrderBean.setEdt(end);
                collector.collect(tradeSkuOrderBean);
            }
        });

        // 异步关联
        SingleOutputStreamOperator<TradeSkuOrderBean> dimStream = AsyncDataStream.unorderedWait(reduceStream, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            AsyncConnection hBaseAsyncConnection;
            StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String table = "dim_sku_info";
                // 获取到SkuID
                String skuId = tradeSkuOrderBean.getSkuId();
                // 从Redis获取数据
                String redisKey = RedisUtil.getRedisKey(table, skuId);

                CompletableFuture.supplyAsync(new Supplier<String>() {
                    @Override
                    public String get() {
                        String dimInfo = null;
                        // 获取Redis数据
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        // 获取Redis数据
                        try {
                            dimInfo = stringRedisFuture.get();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                        return dimInfo;
                    }
                }).thenApplyAsync(new Function<String, JSONObject>() {
                    @Override
                    public JSONObject apply(String dimInfo) {
                        JSONObject objDimInfo = null;
                        if (dimInfo == null || dimInfo.length() == 0) {
                            try {
                                // 从Hbase取
                                objDimInfo = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, table, skuId);
                                // 放到Redis
                                redisAsyncConnection.async().setex(redisKey, 24 * 3600, objDimInfo.toJSONString());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            objDimInfo = JSONObject.parseObject(dimInfo);
                        }
                        return objDimInfo;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject dimInfo) {

                        if (dimInfo != null) {
                            tradeSkuOrderBean.setSpuId(dimInfo.getString("spu_id"));
                            tradeSkuOrderBean.setTrademarkId(dimInfo.getString("tm_id"));
                            tradeSkuOrderBean.setCategory3Id(dimInfo.getString("category3_id"));
//                            System.out.println("tradeSkuOrderBean.getSpuId() = " + tradeSkuOrderBean.getSpuId());
                        } else {
                            System.out.println("查询不到维度数据");
                        }
                        resultFuture.complete(Collections.singletonList(tradeSkuOrderBean));
                    }
                });

            }
        }, 60, TimeUnit.SECONDS);

        // 写出
//        dimStream.print();
//        // 异步关联
        SingleOutputStreamOperator<TradeSkuOrderBean> dimStream1 = AsyncDataStream.unorderedWait(dimStream, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            AsyncConnection hBaseAsyncConnection;
            StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String table = "dim_spu_info";
                // 获取到SkuID
                String spuId = tradeSkuOrderBean.getSpuId();
                // 从Redis获取数据
                String redisKey = RedisUtil.getRedisKey(table, spuId);

                // 以前线程池
                CompletableFuture.supplyAsync(new Supplier<String>() {
                    @Override
                    public String get() {
                        String dimInfo = null;
                        // 获取Redis数据
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        // 获取Redis数据
                        try {
                            dimInfo = stringRedisFuture.get();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                        return dimInfo;
                    }
                }).thenApplyAsync(new Function<String, JSONObject>() {
                    @Override
                    public JSONObject apply(String dimInfo) {
                        JSONObject objDimInfo = null;
                        if (dimInfo == null || dimInfo.length() == 0) {
                            try {
                                // 从Hbase取
                                objDimInfo = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, table, spuId);
                                // 放到Redis
                                redisAsyncConnection.async().setex(redisKey, 24 * 3600, objDimInfo.toJSONString());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            objDimInfo = JSONObject.parseObject(dimInfo);
                        }
                        return objDimInfo;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject dimInfo) {
                        if (dimInfo != null) {
                            String spuName = dimInfo.getString("spu_name");
                            tradeSkuOrderBean.setSpuName(spuName);

                        } else {
                            System.out.println("查询不到维度数据");
                        }
                        resultFuture.complete(Collections.singletonList(tradeSkuOrderBean));
                    }

                });
            }
        }, 60, TimeUnit.SECONDS);

        dimStream1.print();
    }
}
